package com.itdfq.springbootmongodb.domain;

import org.bson.Document;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext;
import org.springframework.data.mongodb.core.query.Query;

/**
 * @author: QianMo
 * @date: 2021/12/22 13:09
 * @mark:
 */
public class GeoNearDocument implements AggregationOperation {

    private Document nearQuery;

    public GeoNearDocument(Query query, Point point, double maxDistance) {
        this.nearQuery = new Document("near", new Document("type", "Point")
                .append("coordinates", new double[]{point.getX(), point.getY()}))
                .append("distanceField", "dist")
                .append("query", query.getQueryObject())
                .append("maxDistance", maxDistance)
                .append("spherical", true);
    }

    /**
     * 需要先创建索引
     *   db.getCollection('storeBean').createIndex({loc: "2dsphere"})
     */

    /*
   db.getCollection('storeBean').aggregate([
   {
     $geoNear: {
        near: { type: "Point", coordinates: [ 114.06821, 22.546212 ] },
        distanceField: "dist",
        maxDistance: 0,
        spherical: true
     }
   },
   {
       $skip:0
    }
   ,
    {
          $limit:20
    }
        ])

     */

    @Override
    public Document toDocument(AggregationOperationContext context) {
        Document command = context.getMappedObject(nearQuery);
        return new Document("$geoNear", command);
    }


}
